#include "Client.hpp"
#include "NetworkHandler.hpp"
#include "Utilities/StringHelper.hpp"
#include "Utilities/FileLogger.hpp"

using namespace std;

int main(int argc, char** argv){
	FileLogger logger;
    Client client;
    
    if(argc == 3){
		client.setup();
        if(client.connect(argv[1], StringHelper::stoi(argv[2])))
            return 0;
    }else{
		//Create request to get server listing.
		sf::Http requestClient;
		requestClient.setHost("http://jmpmain.com/");
		sf::Http::Request listingRequest;
		listingRequest.setUri("ServerTracker/list.php");
		listingRequest.setMethod(sf::Http::Request::Get);
		
		sf::Http::Response listingResponse = requestClient.sendRequest(listingRequest, sf::seconds(3));
		if(listingResponse.getStatus() == sf::Http::Response::Ok){
			
			//Parse xml server listing.
			pugi::xml_document doc;
			pugi::xml_parse_result loadResult = doc.load_buffer(listingResponse.getBody().data(), listingResponse.getBody().size());
			if(loadResult.status != pugi::status_ok)
				return 0;

			vector<string> addresses;
			vector<string> ports;
			pugi::xml_node servers = doc.child("servers");
			if(!servers.empty()){
				int serverCounter = 0;
				//List all server addresses
				cout << "Enter # for server to connect." << endl;
				for(pugi::xml_node server = servers.first_child(); server; server = server.next_sibling()){
					addresses.push_back(server.attribute("ip").value());
					ports.push_back(server.attribute("port").value());
					cout << "#" << serverCounter << ": " << addresses.at(serverCounter) << ":" << ports.at(serverCounter) << endl;
					serverCounter++;
				}
				//If there is only one server select it, otherwise prompt for selection
				int selection = 0;
				if(serverCounter == 1)
					selection = 0;
				else
					cin >> selection;
				client.setup();
				if(client.connect(addresses.at(selection), StringHelper::stoi(ports.at(selection).c_str())))
					return 0;
			}
		}else{
			client.setup();
			if(client.connect("localhost", 60058))
				return 0;
		}
    }
    int retVal = client.run();
    return retVal;
    
}